<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    width="60%"
    :visible.sync="visible"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="80px" @keyup.enter.native="dataFormSubmit()">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="员工照片" prop="staffPhoto" class="unbuttom">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              :on-success="handleAvatarSuccess"
              :action="uploadUrl"
              :with-credentials="true"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="dataForm.staffPhoto" :src="dataForm.staffPhoto" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="用户名" prop="loginname">
            <el-input v-model="dataForm.loginname" show-word-limit clearable maxlength="40" placeholder="登录帐号" />
          </el-form-item>
          <el-form-item label="员工姓名" prop="staffname">
            <el-input v-model="dataForm.staffname" show-word-limit clearable maxlength="25" placeholder="员工姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="工号" prop="staffno">
            <el-input v-model="dataForm.staffno" placeholder="工号" show-word-limit clearable maxlength="20" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!dataForm.id">
        <el-col :span="12">
          <el-form-item label="密码" prop="loginpwd" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.loginpwd" type="password" placeholder="密码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机" prop="staffphone">
            <el-input v-model="dataForm.staffphone" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="staffemail">
            <el-input v-model="dataForm.staffemail" show-word-limit clearable maxlength="100" placeholder="请输入个人邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="角色" size="mini" prop="roleIdList">
            <el-checkbox-group v-model="dataForm.roleIdList">
              <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" size="mini" prop="staffstatus">
            <el-radio-group v-model="dataForm.staffstatus">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" />
      </el-row>
    </el-form>
    <el-row>
      <el-col style="text-align: right;">
        <el-button size="mini" icon="el-icon-close" @click="visible = false">取消</el-button>
        <el-button size="mini" icon="el-icon-check" type="primary" @click="dataFormSubmit()">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile, isNumberOrLetters } from '@/utils/validate'
export default {
  data() {
    var validateNumberOrLetters = (rule, value, callback) => {
      if (!isNumberOrLetters(value)) {
        callback(new Error('只能输入以字母开头并且包含字母或数字以及下划线的字符'))
      } else {
        callback()
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.loginpwd !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      uploadUrl: this.$http.adornUrl(`/system/file/uploadStaffPhoto`),
      roleList: [],
      dataForm: {
        id: 0,
        loginname: '',
        loginpwd: '',
        comfirmPassword: '',
        salt: '',
        staffemail: '',
        staffphone: '',
        roleIdList: [],
        staffstatus: 1,
        staffname: '',
        staffno: '',
        staffPhoto: ''
      },
      dataRule: {
        loginname: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { validator: validateNumberOrLetters, trigger: 'blur' }
        ],
        staffno: [{
          required: true, message: '用户工号不能为空', trigger: 'blur'
        }],
        staffname: [{
          required: true, message: '用户姓名不能为空', trigger: 'blur'
        }],
        loginpwd: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        comfirmPassword: [
          { validator: validateComfirmPassword, trigger: 'blur' }
        ],
        staffemail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        staffphone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleAvatarSuccess(response, file, fileList) {
      if (response.code === 0 && response.file) {
        this.dataForm.staffPhoto = this.$http.adornUrl(`/system/file/downloadStaffPhoto/${response.file.sysFileEncryptionName}`)
      } else {
        this.$message.error(response.msg)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    init(id) {
      this.dataForm.id = id || 0
      this.$http({
        url: this.$http.adornUrl('/role/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.roleList = data && data.code === 0 ? data.list : []
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/user/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.loginname = data.user.loginname
              this.dataForm.salt = data.user.salt
              this.dataForm.staffemail = data.user.staffemail
              this.dataForm.staffphone = data.user.staffphone
              this.dataForm.roleIdList = data.user.roleIdList
              this.dataForm.staffstatus = data.user.staffstatus
              this.dataForm.staffname = data.user.staffname
              this.dataForm.staffno = data.user.staffno
              this.dataForm.staffPhoto = data.user.staffphoto
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/user/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'staffid': this.dataForm.id || undefined,
              'loginname': this.dataForm.loginname,
              'loginpwd': this.dataForm.loginpwd,
              'salt': this.dataForm.salt,
              'staffemail': this.dataForm.staffemail,
              'staffphone': this.dataForm.staffphone,
              'staffstatus': this.dataForm.staffstatus,
              'roleIdList': this.dataForm.roleIdList,
              'staffname': this.dataForm.staffname,
              'staffno': this.dataForm.staffno,
              'staffphoto': this.dataForm.staffPhoto
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .unbuttom{
    margin-bottom: 0px !important
  }
</style>
